package com.ps.controller.user;


import com.ps.constant.StatusConstant;
import com.ps.entity.Medicine;
import com.ps.result.Result;
import com.ps.service.MedicineService;
import com.ps.vo.MedicineVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController("userMedicineController")
@RequestMapping("/user/medicine")
@Slf4j
@RequiredArgsConstructor
@Api(tags = "C端-药品浏览接口")
public class MedicineController {
    private final MedicineService medicineService;
    private final RedisTemplate redisTemplate;

    @GetMapping("/list")
    @ApiOperation("根据分类id查询药品")
    public Result<List<MedicineVO>> list(Long categoryId) {
        //根据分类id生成缓存key
        String key="medicine_"+categoryId;
        //从缓存中获取药品列表
        List<MedicineVO> list = (List<MedicineVO>) redisTemplate.opsForValue().get(key);
        //如果缓存中有药品列表，则直接返回
        if (list != null&& !list.isEmpty()) {
            log.info("缓存命中，直接返回");
            return Result.success(list);
        }
        Medicine medicine = new Medicine();
        medicine.setCategoryId(categoryId);
        medicine.setStatus(StatusConstant.ENABLE);
        list = medicineService.listWithForm(medicine);
        System.out.println(list);
        //将查询结果存入缓存
        redisTemplate.opsForValue().set(key,list);
        //返回查询结果
        log.info("查询结果：{}",list);
        return Result.success(list);
    }

}
